package com.lbs.jiepiaisi.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lbs.jiepiaisi.R;
import com.lbs.jiepiaisi.base.BaseActivity;
import com.lbs.jiepiaisi.bean.WorkOrderListBean;
import com.lbs.jiepiaisi.biz.WorkOrderGetOrderBiz;
import com.lbs.jiepiaisi.fragment.WorkOrderListFragment;
import com.lbs.jiepiaisi.utils.ButtonUtil;
import com.lbs.jiepiaisi.utils.Constant;
import com.lbs.jiepiaisi.utils.WorkOrderEvent;
import com.lbs.jiepiaisi.view.WaitingDialogControll;
import com.lbs.jiepiaisi.view.WorkOrderSingleView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.LinkedHashMap;

public class WorkOrderAddActivity extends BaseActivity {

    private WorkOrderListBean.Result.Item mWorkOrder;

    public static final String DEVICE_RECEIVER = "WorkOrderAddActivity_DEVICE_RECEIVER";

    private TextView mName;
    private TextView mTel;
    private TextView mTime;
    private TextView mDis;
    private TextView mPaiName;
    private TextView mPaiTel;
    private TextView mOrderCode;
    private TextView mOrderType;
    private TextView mOrderOrgan;
    private TextView mJingXiaoShang;
    private TextView mCheXing;
    private TextView mCheJia;
    private TextView mChePai;
    private TextView mBeiZhu;

    private Button mOk;

    private LinearLayout mDeviceLin;

    private DeviceReceiver mDeviceReceiver;

    private OkReceiver mOkReceiver;

    private LinkedHashMap<String,String> mDeviceMap = new LinkedHashMap<>();

    private static final String WORK_ORDER_ADD="com.lbs.jiepiaisi.activity.WorkOrderAddActivity";

    //存放设备号
    private LinkedHashMap<String,String> workEqnos = new LinkedHashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isTemplate = true;
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.activity_work_order_add);
        EventBus.getDefault().register(this);
        init();
    }

    private void init(){
        getExtra();
        initView();
        setListener();
        setDevices();
    }


    private void getExtra(){
        mWorkOrder = (new Gson().fromJson(getIntent().getStringExtra("order"),WorkOrderListBean.Result.Item.class));
        setWorkEqnosPre();
    }

    private void setWorkEqnosPre(){
        if(mWorkOrder.getWorkEqnos() != null){
            String wE  = mWorkOrder.getWorkEqnos().trim();
            if(wE.contains(",")){
                String[] wEs = wE.split(",");
                for(int i =0 ;i < wEs.length;i ++){
                    String t = wEs[i];
                    if(t != null && t.length() == 16){
                        Log.e("order",t.subSequence(15,16) + ","+t.subSequence(0,15).toString());
                        workEqnos.put(t.subSequence(15,16).toString(),t.subSequence(0,15).toString());
  //                      oldNum++;
                        mWorkEqs = mWorkEqs + t + ",";
                    }
                }
                mWorkEqs = mWorkEqs.substring(0,mWorkEqs.lastIndexOf(","));
                Log.e("mWorkEqs",mWorkEqs);

            }
            if(!wE.contains(",") && wE.length() > 5){
                String t = mWorkOrder.getWorkEqnos();
                if(t != null ){
                    if(t.length() == 16){
                        Log.e("order",t.subSequence(15,16) + ","+t.subSequence(0,15).toString());
                        workEqnos.put(t.subSequence(15,16).toString(),t.subSequence(0,15).toString());
 //                       oldNum++;
                        mWorkEqs = mWorkEqs + t ;
                    }
                }
                Log.e("mWorkEqs",mWorkEqs);
            }
            if(!wE.contains(",") && wE.length() != 16){
                mWorkEqs = "";
            }
        }
        Log.e("finish",mWorkEqs);


    }
    private void setDevices(){
        if(mWorkOrder.getWorkEqnos() != null){
            String wE  = mWorkOrder.getWorkEqnos().trim();
            if(wE.contains(",")){
                String[] wEs = wE.split(",");
                for(int i =0 ;i < wEs.length;i ++){
                    String t = wEs[i];
                    if(t != null && t.length() == 16){
                        Device device  = mDeviceMapUpdate.get(""+t.subSequence(15,16).toString());
                        device.setNum(t.subSequence(0,15).toString());
                        mDeviceMapUpdate.put(""+t.subSequence(15,16).toString(),device);
                    }
                }

            }
            if(!wE.contains(",") && wE.length() > 5){
                String t = mWorkOrder.getWorkEqnos();
                if(t != null ){
                    if(t.length() == 16){
                        Device device  = mDeviceMapUpdate.get(""+t.subSequence(15,16).toString());
                        device.setNum(t.subSequence(0,15).toString());
                        mDeviceMapUpdate.put(""+t.subSequence(15,16).toString(),device);
                    }
                }
            }
        }


    }

    private void initView(){
        titleView.setText("安装拍照");

        mName = (TextView)findViewById(R.id.tv_name);
        mTel = (TextView)findViewById(R.id.tv_tel);
        mTime = (TextView)findViewById(R.id.tv_time);
        mDis = (TextView)findViewById(R.id.tv_dis);
        mPaiName = (TextView)findViewById(R.id.tv_paidan_name);
        mPaiTel = (TextView)findViewById(R.id.tv_paidan_tel);
        mOrderCode = (TextView)findViewById(R.id.tv_order_code);
        mOrderType = (TextView)findViewById(R.id.tv_order_type);
        mOrderOrgan = (TextView)findViewById(R.id.tv_order_organ);
        mJingXiaoShang = (TextView)findViewById(R.id.tv_jingxiaoshang);
        mCheXing = (TextView)findViewById(R.id.tv_chexing);
        mCheJia = (TextView)findViewById(R.id.tv_chejia);
        mChePai = (TextView)findViewById(R.id.tv_chepai);
        mBeiZhu = (TextView)findViewById(R.id.tv_beizhu);
        mDeviceLin  = (LinearLayout)findViewById(R.id.lin_device_list);
        mOk = (Button)findViewById(R.id.btn_ok);

        mName.setText(mWorkOrder.getSiteContact());
        mTel.setText(mWorkOrder.getSiteContactTel());
        mTime.setText(mWorkOrder.getPreInstallTime());
        mDis.setText(mWorkOrder.getInstallSite());
        mPaiName.setText(mWorkOrder.getCharger());
        mPaiTel.setText(mWorkOrder.getChargerTel());
        mOrderCode.setText(mWorkOrder.getWorkOrderNo());
        setType(mWorkOrder.getWordOrderType());
        mOrderOrgan.setText(mWorkOrder.getInstaller());
        mJingXiaoShang.setText(mWorkOrder.getCompany());
        mCheXing.setText(mWorkOrder.getCarType());
        mCheJia.setText(mWorkOrder.getVin());
        mChePai.setText(mWorkOrder.getCarNo());
        mBeiZhu.setText(mWorkOrder.getWorkComments());

        setDeviceMap(mWorkOrder.getInstallComments());

        mDeviceReceiver = new DeviceReceiver();
        mOkReceiver = new OkReceiver();

        IntentFilter intentFilterDevice = new IntentFilter(DEVICE_RECEIVER);

        getApplicationContext().registerReceiver(mDeviceReceiver,intentFilterDevice);

        IntentFilter intentFilterOK = new IntentFilter(WORK_ORDER_ADD);
        getApplicationContext().registerReceiver(mOkReceiver,intentFilterOK);

    }

    private void setListener(){
        //上传所有工单，工单完成
        mOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(deviceNum <= (getDeviceNum()) || deviceNum == 0){
                    if(ButtonUtil.isFastClick()){
                        WaitingDialogControll.showWaitingDialog(WorkOrderAddActivity.this);
                        new WorkOrderGetOrderBiz().getOrderBiz(mWorkOrder.getWoId(),Constant.WORK_ORDER_HISTORY_GET,mWorkEqs, WORK_ORDER_ADD,false);
                    }
                }else {
                    Toast.makeText(WorkOrderAddActivity.this, "当前工单未完成，请稍候再试", Toast.LENGTH_SHORT).show();
                }
//                if(ButtonUtil.isFastClick()){
//                    WaitingDialogControll.showWaitingDialog(WorkOrderAddActivity.this);
//                    new WorkOrderGetOrderBiz().getOrderBiz(mWorkOrder.getWoId(),Constant.WORK_ORDER_HISTORY_GET,mWorkOrder.getWorkEqnos(), WorkOrderListFragment.WORK_ORDER_REFRESH);
//                }


            }
        });
    }

    private void setType(String wType){
        if("0".equals(wType)){
            mOrderType.setText("新装");
        }else if("1".equals(wType)){
            mOrderType.setText("维护");
        }else if("2".equals(wType)){
            mOrderType.setText("拆机");
        }else if("3".equals(wType)){
            mOrderType.setText("移机");
        }else if("4".equals(wType)){
            mOrderType.setText("家访");
        }
    }

    private void setDeviceMap(String device){
        String devices;
        devices = device.replaceAll(" ","");
        devices = devices.replaceAll("，",",");
        devices = devices.replaceAll("X","x");
        Log.e("device",devices);
        if(!devices.contains(",")){
            String[] data = devices.split("x");
            if(data.length >= 2){
                mDeviceMap.put(data[0],data[1]);
                addDeviceView(mDeviceMap);
            }

        }else {
            String[] out = devices.split(",");
            for(String inn : out){
                String[] data = inn.split("x");
                if(data.length >= 2){
                    mDeviceMap.put(data[0],data[1]);

                }
            }
            addDeviceView(mDeviceMap);
        }



    }
    LinkedHashMap<String,Device> mDeviceMapUpdate = new LinkedHashMap<>();
    LinkedHashMap<String,WorkOrderSingleView> mDeviceMapView = new LinkedHashMap<>();
    private int deviceNum = 0;
    private void addDeviceView(HashMap<String,String> mDeviceMap){
        int i = 0;
        for(String key : mDeviceMap.keySet()){
            int num = Integer.parseInt(mDeviceMap.get(key)) ;
            deviceNum += num;
            while (num > 0){
                WorkOrderSingleView workOrderSingleView = new WorkOrderSingleView(this);
                workOrderSingleView.setContent(i,key,"1",workEqnos);
                num--;
                mDeviceLin.addView(workOrderSingleView);

                Device device = new Device();
                device.setName(key);
                device.setNum("1");
                mDeviceMapUpdate.put(""+i,device);
                mDeviceMapView.put(""+i,workOrderSingleView);
                i++;
            }
        }

    }
    //更新工单状态
    private void updateDevices(String[] datas){
//        if(!isHave(datas[1])){
//            Device device  = mDeviceMapUpdate.get(""+datas[0]);
//            device.setNum(datas[1]);
//            mDeviceMapUpdate.put(""+datas[0],device);
//            mDeviceMapView.get(""+datas[0]).updateContent(datas[1]);
//
//            String wOnlyOne  = getWorkEqs(device.getNum(),""+datas[0]);
//            Log.e("work",wOnlyOne);
//            new WorkOrderGetOrderBiz().getOrderBiz(mWorkOrder.getWoId(),Constant.WORK_ORDER_HAVE_GET,wOnlyOne,WorkOrderListFragment.WORK_ORDER_REFRESH,false);
//
//        }else {
//            Toast.makeText(this,"此设备已经上传",Toast.LENGTH_SHORT).show();
//        }

        Device device  = mDeviceMapUpdate.get(""+datas[0]);
        device.setNum(datas[1]);
        mDeviceMapUpdate.put(""+datas[0],device);
        mDeviceMapView.get(""+datas[0]).updateContent(datas[1]);

        String wOnlyOne  = getWorkEqs(device.getNum(),""+datas[0]);
        Log.e("work",wOnlyOne);
        new WorkOrderGetOrderBiz().getOrderBiz(mWorkOrder.getWoId(),Constant.WORK_ORDER_HAVE_GET,wOnlyOne,WorkOrderListFragment.WORK_ORDER_REFRESH,false);


    }

    private String mWorkEqs = "";
    private String getWorkEqs(String deviceCode,String position){
        String f = "";
        if(mWorkEqs.contains(",")){
            f = ",";
        }else if(mWorkEqs != null && workEqnos.toString().trim().length() > 0){
            f = ",";
        }
        mWorkEqs = mWorkEqs + f + deviceCode + position;
        Log.e("mWorkEqs",mWorkEqs);
        if(mWorkEqs.indexOf(",") < 16){
            mWorkEqs = mWorkEqs.substring(mWorkEqs.indexOf(",")+1,mWorkEqs.length());
        }
        Log.e("mWorkEqs","code:"+deviceCode +",position:"+position);
        Log.e("mWorkEqs",mWorkEqs);
        return mWorkEqs;
    }

    public boolean isHave(String data){
        for(String key : mDeviceMapUpdate.keySet()){
            if(mDeviceMapUpdate.get(key).getNum().equals(data)){
                return true;
            }
        }
        return false;
    }

    private int getDeviceNum(){
        int num = 0;
        for(String key : mDeviceMapUpdate.keySet()){
            if(mDeviceMapUpdate.get(key).getNum() != null && mDeviceMapUpdate.get(key).getNum() .length() > 10){
                num ++;
            }
        }
        return num;
    }
    //初始化工单
    class DeviceReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String data = intent.getStringExtra("data");
            if(data.contains(",")){
                String[] datas = data.split(",");
                updateDevices(datas);
            }

        }
    }

    //上传所有工单
    class OkReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            int status = intent.getIntExtra(Constant.KEY_DATA,-1);
            WaitingDialogControll.dismissWaitingDialog();
            if(status == Constant.STATUS_OK){
                getApplicationContext().sendBroadcast(new Intent(WorkOrderListFragment.WORK_ORDER_REFRESH));
//                if(ToastUtil.isFastShow()){
                    Toast.makeText(WorkOrderAddActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
                    finish();
//                }
            }else {
//                if(ToastUtil.isFastShow()){
                    Toast.makeText(WorkOrderAddActivity.this, "操作失败,请重新操作", Toast.LENGTH_SHORT).show();
//                }
            }
        }
    }
    class Device{
        private String name;
        private String num;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getNum() {
            return num;
        }

        public void setNum(String num) {
            this.num = num;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if(mDeviceReceiver != null){
            getApplicationContext().unregisterReceiver(mDeviceReceiver);
        }
        if(mOkReceiver != null){
            getApplicationContext().unregisterReceiver(mOkReceiver);
        }
    }

    //接收图片上传后返回结果
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDataSynEvent(WorkOrderEvent workOrderEvent) {
        if(workOrderEvent.getMessage().contains(",")){
            String[] datas = workOrderEvent.getMessage().split(",");
            updateDevices(datas);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
}
